package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"sys-proj/cache"
	"sys-proj/models"
	"time"
)

// 文章发布
func ArticleAdd(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	if title == "" || content == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "文件添加失败",
		})
		return
	}
	data := models.Article{
		Title:   title,
		Content: content,
	}

	redis_key := "article_add" + strconv.Itoa(int(data.ID))
	var article models.Article
	models.DB.Where("id=?", data.ID).First(&article)
	jsonData, _ := json.Marshal(article)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)

	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return
}

// 文章删除
func Del(c *gin.Context) {
	id := c.Query("id")
	var del models.Article
	err := models.DB.Delete(&del, id).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}
